package com.bestcem.xm.common.core.config.mq;

import com.bestcem.xm.common.core.uitls.MsgPackFormatUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.converter.AbstractMessageConverter;

@Slf4j
public class XmCustomMessageConverter extends AbstractMessageConverter {

    @Override
    protected boolean supports(@NotNull Class<?> clazz) {
        return true;
    }

    @Override
    protected Object convertFromInternal(Message<?> message, @NotNull Class<?> targetClass, Object conversionHint) {
        //处理发送数据
        Object payload = message.getPayload();
        if (payload instanceof byte[]) {
            try {
                return MsgPackFormatUtil.decode((byte[]) message.getPayload(), targetClass);
            } catch (Exception e) {
                log.error("convertFromInternal error: payload:{}, targetClass:{}, conversionHint:{}", message.getPayload(), targetClass.getName(), conversionHint);
                return null;
            }
        }
        return payload;
    }

    @Override
    protected Object convertToInternal(@NotNull Object payload, MessageHeaders headers, Object conversionHint) {
        //处理接收数据
        try {
            return MsgPackFormatUtil.encode(payload);
        } catch (JsonProcessingException e) {
            log.error("convertToInternal error: payload:{}, targetClass:{}, conversionHint:{}", payload, headers, conversionHint);
            return payload;
        }
    }
}
